package com.start.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.start.admin.entity.StartSysDictionary;
import com.start.admin.entity.StartSysDictionaryItem;
import com.start.admin.mappers.SysDictionaryItemMapper;
import com.start.admin.mappers.SysDictionaryMapper;
import com.start.admin.service.StartSysDictionaryItemService;
import com.start.common.exceptions.StartBusException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StartSysDictionaryItemServiceImpl extends ServiceImpl<SysDictionaryItemMapper, StartSysDictionaryItem> implements StartSysDictionaryItemService {
    @Autowired
    private SysDictionaryMapper sysDictionaryMapper;

    @Override
    public void saveDictionaryItem(StartSysDictionaryItem entity) {
        if (StringUtils.isEmpty(entity.getDictionaryId())) throw new StartBusException("父级字典id不能为空");
        StartSysDictionary startSysDictionary = sysDictionaryMapper.selectById(entity.getDictionaryId());
        if (startSysDictionary == null) throw new StartBusException("父级字典不存在");
        if (StringUtils.isEmpty(entity.getDictCode())) throw new StartBusException("当前字典编码不能为空");
//        if (entity.getDictCode().contains(":")) throw new StartBusException("字典编码不能包含‘:’符号");
        entity.setDictCode(startSysDictionary.getDictCode() + ":" + entity.getDictCode());
        save(entity);
    }

    @Override
    public List<StartSysDictionaryItem> listByDictionaryCode(String code) {
        LambdaQueryWrapper<StartSysDictionary> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StartSysDictionary::getDictCode, code);
        List<StartSysDictionary> sysDictionaries = sysDictionaryMapper.selectList(wrapper);
        if (sysDictionaries.size() < 1) return null;
        StartSysDictionary startSysDictionary = sysDictionaries.get(0);
        return listByDictionaryId(startSysDictionary.getId());
    }

    @Override
    public List<StartSysDictionaryItem> listByDictionaryId(String dictionaryId) {
        LambdaQueryWrapper<StartSysDictionaryItem> itemLambdaQueryWrapper = new LambdaQueryWrapper<>();
        itemLambdaQueryWrapper.eq(!StringUtils.isEmpty(dictionaryId), StartSysDictionaryItem::getDictionaryId, dictionaryId);
        itemLambdaQueryWrapper.eq(StartSysDictionaryItem::getIsEnable, 1);
        itemLambdaQueryWrapper.orderByAsc(StartSysDictionaryItem::getDictionaryId);
        itemLambdaQueryWrapper.orderByAsc(StartSysDictionaryItem::getDictSort);
        return list(itemLambdaQueryWrapper);
    }
}
